import {
  valueWatch,
  getIdShowTextFromUserInfo,
  getUserInfoFromStorage,
  setUserInfoIntoStorage,
  checkUserInfo,
} from '../../utils/common.js'
// 引入coolsite360交互配置设定
require('coolsite.config.js');
// import {
//   setStorageFormUserInfoAndGopage
// } from '../../utils/who.js';
import {
  roleDict,
  schoolList,
  roleList,
  classNumberList,
  gradeNumberList,
  roomList,
} from '../../config.js';
// 获取全局应用程序实例对象
var app = getApp();


// 创建页面实例对象
Page({
  /**
   * 页面名称
   */
  name: "five",
  /**
   * 页面的初始数据
   */

  renderUserInfo(userInfo) {
    // const wxopenid = that.fetchWxopenid().then(wxopenid=>{
    const that = this;
    const idShowText = getIdShowTextFromUserInfo.apply(that, [userInfo]);
    that.setTitle(userInfo.userid);
    const valueKeyedUserInfoDict = {}
    Object.keys(userInfo).forEach(key => {
      let modifiedKey = key;
      switch (key) {
        case 'class':
          modifiedKey = 's_class';
          valueKeyedUserInfoDict[`${modifiedKey}.value`] = userInfo[key]
          break;
        case 'grade':
          modifiedKey = 's_grade';
          valueKeyedUserInfoDict[`${modifiedKey}.value`] = userInfo[key]
          break;
        case 'role':
          modifiedKey = 'role';
          valueKeyedUserInfoDict[`${modifiedKey}.value`] = roleDict[userInfo['role']].text
          break;
        default:
          valueKeyedUserInfoDict[`${key}.value`] = userInfo[key];
      }
    });
    that.setData({
      ...valueKeyedUserInfoDict,
      idShowText,
    });
    let userInfoDict = wx.getStorageSync('userInfoDict')
    if (Object.prototype.toString.call(userInfoDict) !== '[object Object]') {
      userInfoDict = {};
    }
    userInfoDict[userInfo.wxopenid] = userInfo;
    wx.setStorageSync('userInfoDict', userInfoDict)
  },

  /**
   * 生命周期函数--监听页面显示
   */

  setTitle(userid){
    const userFormTitle = userid ? '修改用户信息' : '添加用户信息';
    console.log(`40-40 userForm.js renderUserInfo::::: userFormTitle: ${userFormTitle} , userid: ${userid}`);
    wx.setNavigationBarTitle({title:userFormTitle,});
  },

  onShow() {
    // 执行coolsite360交互组件展示
    const that = this;
    app.coolsite360.onShow(this);
    let userInfo = getUserInfoFromStorage();
    if (userInfo) {
      that.renderUserInfo(userInfo);
    } else {
      that.fetchWxopenid().then(wxopenid => {
        // if (!wxopenid) {
        //   console.log(`40-40 userForm.js method:::::onShow:::wxopenid: ${wxopenid} , onShow hook method just run here , return ...`);
        //   return;
        // }
        const noCacheHash = Date.now();
        const readUserUrl = `http://localhost/read_user_by_wxopenid?wxopenid=${wxopenid}&noCacheHash=${noCacheHash}`;
        wx.request({
          url: readUserUrl,
          method: 'GET',
          fail(err) {
            console.log(`45-45 userForm.js method:::::onShow::: wx.request readUserUrl: ${readUserUrl} , response err: `, err);
          },
          success(res) {
            console.log(`48-48 userForm.js method:::::onShow::: wx.request readUserUrl: ${readUserUrl} , res: `, res);
            const userInfo = res.data;
            if (checkUserInfo(userInfo)) {
              that.renderUserInfo(userInfo);
            }else{
              that.setTitle(null);
            }
          },
        })
      });
    }

  },



  listToDict(list) {
    return list.map((item, index) => ({
      text: item,
      value: item
    }))
  },

  data: {

    // value1: 0,
    // schoolIndex: 0,
    // value2: 0,

    idShowText: '',
    userid: {
      value: '',
      ts: '',
      hidden: false,
      dictList: null,
    },
    name: {
      value: '',
      ts: '请填入真实姓名',
      hidden: false,
      dictList: null,
    },
    school: {
      value: schoolList[0],
      ts: '',
      hidden: false,
      dictList: schoolList.map(item => ({
        text: item,
        value: item
      })),
    },
    role: {
      value: roleDict[roleList[0]].text,
      ts: '',
      hidden: false,

      dictList: roleList.map(role => ({
        text: roleDict[role].text,
        value: roleDict[role].text,
        moduleName: roleDict[role].moduleName,
      })),
    },
    s_grade: {
      value: gradeNumberList[0],
      ts: '',
      hidden: false,
      dictList: gradeNumberList.map(item => ({
        text: item,
        value: item
      })),
    },
    s_class: {
      value: classNumberList[0],
      ts: '',
      hidden: false,
      dictList: classNumberList.map(item => ({
        text: item,
        value: item
      })),
    },
    room: {
      value: roomList[0],
      ts: '',
      hidden: false,
      dictList: roomList.map(item => ({
        text: item,
        value: item
      })),
    },


    roles: [{
        value: 11,
        text: '学生'
      },
      {
        value: 0,
        text: '授课老师'
      },
      {
        value: 1,
        text: '辅导员'
      }
    ],
    roleIndexList: [0],
    // role: 11,

    modalHidden: false,
    ts1: '请确保无误再提交',
    ts2: '两次密码不一致',
    ts1hidden: true,
    ts2hidden: true,
    id: ''
  },
  bindRoleChange(e) { //单独写一份role的select监听函数，方便定制
    console.log(`66-66 bindRoleChange:::e:`, e);
    const values = e.detail.value;
    const index = values[0];
    console.log(`69-69 bindRoleChange index:${index}`);
    const roleValueKey = `role.value`;
    const roleTextKey = `role.text`;
    this.setData({
      roleIndexList: index,
      [roleValueKey]: this.data.roles[index].value,
      [roleTextKey]: this.data.roles[index].text,
    })
  },
  fetchWxopenid() {
    const that = this;
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: "getOpenid",
        success(res) {
          console.log(`99-99 method:::::wxAuth:::res: `, res);
          var wxopenid = res.result.openid;
          app.globalData.wxopenid = wxopenid;
          that.setData({
            wxopenid,
          });
          console.log('请求获取wxopenid:', wxopenid);
          wx.setStorageSync('wxopenid', wxopenid)
          resolve(wxopenid);
          // app._getUserInfo();
          // that.fetchUserInfoFromBackendFlow(wxopenid, needAuthedRedirect)
        },
        fail(err) {
          const errMsg = `211-211 userForm.js method:::::fetchWxopenid:::err:`
          console.log(errMsg, err);
          wx.showToast({
            title: '获取openid时微信授权异常,请检查网络并登录微信',
            icon: 'none',
          })
          reject(errMsg);
        }
      });
    });

  },
  selectValueWatch(e) {
    console.log(`142-142 method:::::selectValueWatch:::e:`, e);
    // 绑定到valueValue的e.currentTarget需要有data-name属性,详见 utils/common.js 注视
    valueWatch.apply(this, [e, e.detail]);
  },
  valueWatch(e) {
    // 绑定到valueValue的e.currentTarget需要有data-name属性,详见 utils/common.js 注视
    valueWatch.apply(this, [e]);
  },
  submit: function () {
    const that = this;
    if (!that.data.name.value) {
      wx.showToast({
        title: '请填入真实姓名',
        image: '/resources/icon_warning.png'
      })
      return;
    }
    if (that.data.role.value == '学生' || that.data.role.value == '11') {
      if (!that.data.s_grade.value) {
        wx.showToast({
          title: '学生应该选择年级',
          image: '/resources/icon_warning.png'
        });
        return;
      }
      if (!that.data.s_class.value) {
        wx.showToast({
          title: '学生应该选择班级',
          image: '/resources/icon_warning.png'
        });
        return;
      }
    }
    // if (!this.data.ts2hidden) {
    //   this.setData({
    //     ts1hidden: false
    //   })
    //   return;
    // }
    // var student_id = wx.getStorageSync('student_id');
    const wxopenid = wx.getStorageSync('wxopenid')
    const userid = that.data.userid.value;
    const roleShowValue = this.data.role.value;
    const role = roleDict[roleShowValue].submitValue;
    let userInfo = {
      userid,
      wxopenid,
      name: that.data.name.value,
      school: that.data.school.value,
      role,
      student_id: role == '11' ? userid : undefined,
      teacher_id: role == '11' ? userid : undefined,
      s_class: role == '11' ? that.data.s_class.value : undefined,
      s_grade: role == '11' ? that.data.s_grade.value : undefined,
      room: role == '11' ? that.data.room.value : undefined,
    }
    userInfo = JSON.parse(JSON.stringify(userInfo)); // 这一句是去除上userInfo对象中值为undefined的项
    const editUserApi = `${app.globalData.apiBaseUrl}/edit_user`
    wx.request({
      url: editUserApi,
      data: {
        ...userInfo,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      fail(err) {
        console.log(`method:::::submit::: wx.request editUserApi: ${editUserApi} , response err: `, err);
      },
      success: function (res) {
        console.log(res);
        if (res["data"] == "edit_user method True") {
          setUserInfoIntoStorage(userInfo);
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 1000
          })
          const mePageUrl = `/page/${roleDict[role]['moduleName']}/page/five/five?needAuthedRedirect=1`;
          // setStorageFormUserInfoAndGopage(userInfo);
          wx.redirectTo({
            url: mePageUrl,
          })
        }
        //  else {
        //   ts1: '出现错误了<(￣3￣)> '
        //   ts1hidden: true
        // }
      }
    })
    // wx.navigateBack({});


  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    app.editTabBar();
    // 注册coolsite360交互模块
    app.coolsite360.register(this);
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: getApp().globalData.warmBgColor
    });
    // var student_id = wx.getStorageSync('student_id');
    // this.setData({
    //   id: student_id
    // });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },


  //以下为自定义点击事件
  goBack: function () {
    wx.redirectTo({
      url: '/page/student/page/five/five?needAuthedRedirect=1',
    })
  },

  toOpenRoomList() {
    wx.showLoading({
      title: '正在加载',
    })
  },

})